/**
 * 
 */
package com.jfinal.ext.interceptor;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.log.Log;
import com.jfinal.server.ExceptionAdvisor;

/**
 * @author y.z
 * exception By Controller
 * 异常统一处理
 */
public class ExceptionInterceptor implements Interceptor{
	private static final Log log = Log.getLog(ExceptionInterceptor.class);
	/* (non-Javadoc)
	 * @see com.jfinal.aop.Interceptor#intercept(com.jfinal.aop.Invocation)
	 */
	@Override
	public void intercept(Invocation inv) {
		try{
			inv.invoke();
		}catch(Exception e){
			ExceptionAdvisor.getExceptionInfo(e,inv);
			exceptionHandler(inv);
		}
		
	}
	
	
	/**
	 * 异步异常处理
	 * @param inv
	 */
	private void exceptionHandler(Invocation inv){
		String ajax = inv.getController().getRequest().getHeader("X-Requested-With");
		
		if("XMLHttpRequest".equals(ajax)){
			Map<String,String> ret = new HashMap<String,String>();
			ret.put("code","0");
			ret.put("msg","系统异常");
			inv.getController().renderJson(ret);
		}else{
			inv.getController().render("/pages/505.html");
		}
	}

}
